WPF中RadioButton的分组 |
您所在的位置:网站首页 › view change button › WPF中RadioButton的分组 |
当界面上出现多组Radiobutton时,将所有的Radiobutton写在同一个Grid里面,导致系统认为所有的Radiobutton是同一组,造成选择混乱,解决的方法: 1.要为属于同个组的Radiobutton设置相同的GroupName,绑定同一个变量; 2.若没有为Radiobutton设置GroupName,则将属于同一组的Radiobutton放在一个容器中,如wrappannel里面。 通常为Radiobutton设置转化器,将不同的button上对应的值,与选中与不选中进行转换,下面展示例子,示例中有三种转换器:EnumToBoolConverter,IntToBoolConverter,FloatToBoolConverter。代码如下(示例采用的MVVM模式): ///model中代码 public enum ProtocolTypeDefine { RS232, RS485 } private ProtocolTypeDefine _protocolType; private int _dataBits; private float _stopBits; /// /// 协议类型 /// public ProtocolTypeDefine ProtocolType { get { return _protocolType; } set { _protocolType = value; RaisePropertyChanged( ()=>ProtocolType ); } } /// /// 数据位 /// public int DataBits { get { return _dataBits; } set { _dataBits = value; RaisePropertyChanged( ()=> DataBits ); } } /// /// 停止位 /// public float StopBits { get { return _stopBits; } set { _stopBits = value; RaisePropertyChanged( ()=>StopBits ); } }
//view.xaml中代码 //view.cs中的代码 public class EnumToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int data = (int)value; string name = parameter.ToString(); switch (name) { case "0": return data == 0; case "1": return data == 1; default: return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (ProtocolTypeDefine)int.Parse(parameter.ToString()); } } public class IntToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int data = (int)value; string name = parameter.ToString(); switch (name) { case "6": return data == 6; case "7": return data == 7; case "8": return data == 8; default: return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var data = (bool)value; if (data) { return System.Convert.ToInt32(parameter); } return -1; } } public class FloatToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { float data = 0f; if (!float.TryParse(value.ToString(), out data)) { return false; } string name = parameter.ToString(); switch (name) { case "1": return data == 1; case "1.5": return data == 1.5; case "2": return data == 2; default: return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var data = (bool)value; if (data) { return System.Convert.ToSingle(parameter); } return -1; } }
//model中代码 //协议 SerialSetModel.ProtocolType = 0; //数据位 SerialSetModel.DataBits = 8; //停止位 SerialSetModel.StopBits = 1;
在此只贴出重要部分代码,使用时只要按照该原理进行组装即可。
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |